from ip2031 import *
import pygst
pygst.require('0.10')
import gst
import gobject

import sys

class JPEGSrc(gst.PushSrc):
    """
    """

    def __init__(self, name, caps = gst.caps_new_any()):
        self.__gobject_init__()

        _srcpadtemplate = gst.PadTemplate ("srcpadtemplate",
                                        gst.PAD_SRC,
                                        gst.PAD_ALWAYS,
                                        caps)

        self.set_name(name)
        self.srcpad = gst.Pad(_srcpadtemplate, 'src')
        #self.srcpad.set_event_function(self.eventfunc)
        self.add_pad(self.srcpad)            

    def newPacket(self, data):
        """
        Push the packet data down stream
        """
        self.srcpad.push(gst.Buffer(data))

    def eventfunc(self, pad, event):
        print ("%s event:%r" % (pad, event.type))
        return True

gobject.type_register(JPEGSrc)

class Animator:
    def __init__(self):
        gobject.timeout_add(150, self.callback)

        pipeline = gst.Pipeline()
        self.src = JPEGSrc("src")
        decoder = gst.element_factory_make('jpegdec')
        sink = gst.element_factory_make('xvimagesink')           
        pipeline.add(self.src, decoder, sink)
        gst.element_link_many(self.src, decoder, sink)
        pipeline.set_state(gst.STATE_PLAYING)
        self.oldT = None

    def callback(self):
        import time ; t = time.time()
        if self.oldT != None:
            print t - self.oldT
        img = x.getImage()
        self.src.newPacket(img)
        self.oldT = t
        return True
x = IP2031(sys.argv[1], int(sys.argv[2]))
x.disconnect()
x.connect()
a = Animator()
gobject.MainLoop().run()

x.disconnect()
